#-*- coding:UTF-8 -*-
"""
controller: Index

Version: v1
Last Modified: Mar 1,2009
All rights reserved
"""
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import memcache
from google.appengine.runtime import apiproxy_errors
from google.appengine.api import mail
import os
import logging
import random
import time
from model import *


class Index(webapp.RequestHandler):
    def post(self):
        self.get()        
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        self.response.out.write(template.render(path,[]))

class Login(webapp.RequestHandler):
    def post(self):
        result= {}
        email=self.request.get("email")
        password=self.request.get("password")
        users=db.GqlQuery("SELECT * FROM User WHERE email=:1",email)
        R=False
        for u in users:
            R=True
            if u.password==password:
                sessionkey=str(random.random())+"-"+str(time.time())
                self.response.headers.add_header('Set-Cookie','sessionkey=%s;' \
                                                           % sessionkey)
                session=Session()
                session.sessionkey=sessionkey
                session.addr=self.request.remote_addr
                session.expire=False
                session.email=email
                session.nickname=u.nickname
                session.userid=u.userid
                session.put()
                self.redirect("/admin")
            else:
                R=False
                
        if R==False:
            template_values = {"msg":"Login Failed"}
            path = os.path.join(os.path.dirname(__file__), 'templates/login.html')
            self.response.out.write(template.render(path,template_values))
        
    def get(self):
        template_values = {"msg":""}
        path = os.path.join(os.path.dirname(__file__), 'templates/login.html')
        self.response.out.write(template.render(path,template_values))
        
class Logout(webapp.RequestHandler):
    def post(self):
        self.get()
        
    def get(self):
        sessionkey=self.request.cookies.get("sessionkey","NULL")
        session = db.GqlQuery ("SELECT * FROM Session WHERE sessionkey=:1",sessionkey)
        for s in session:
            s.expire=True
            s.put()
        self.redirect("/index")

class Register(webapp.RequestHandler):
    def post(self):
        result= {}
        email=self.request.get("email")
        password=self.request.get("password")
        query=db.GqlQuery("SELECT * FROM User WHERE email=:1",email)
        R=True
        resultstr="Register Successfully"
        for u in users:
            R=False
            resultstr="Register Failed. The Email %s has been registered."%email
        if R:
            users=db.GqlQuery("SELECT * FROM User ORDER BY userid DESC LIMIT 1")
            uid=0
            for u in users:
                uid=u.userid
            usr=User()
            usr.userid=uid+1
            usr.email=email
            usr.password=password
            usr.nickname=email
            usr.valid=0
            usr.put()
        result["resultstr"]=resultstr
        path = os.path.join(os.path.dirname(__file__), 'templates/register.html')
        self.response.out.write(template.render(path,result))
        
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'templates/register.html')
        self.response.out.write(template.render(path,[]))
                
class NotFound(webapp.RequestHandler):
    def post(self):
        self.get()
        
    def get(self):
        request_url=self.request.url
        logging.info("Requesting no exist url: %s"%request_url)
        template_values={
                         "request_url":request_url
                         }
        path = os.path.join(os.path.dirname(__file__), 'templates/notfound.html')
        self.response.out.write(template.render(path,template_values))
                
def main():
    application = webapp.WSGIApplication([
                                      ('/register/?',Register),
                                      ('/login/?',Login),
                                      ('/logout/?',Logout),
                                      ('/index/?',Index),
                                      ('/?',Index),
                                      ('/.*',NotFound)
                                      ],debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()